﻿using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ViewMaker.Core.Silverlight
{
    [Export(typeof(IXamlGenerator))]
    public class SlXamlGenerator : IXamlGenerator
    {
        public static string Template { get; set; }
        
        static SlXamlGenerator()
        {
            Template = 
@"<ContentControl 
    xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation""
    xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml""                                  
    xmlns:sdk=""http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"" 
    xmlns:vg=""ViewMaker.Core.Silverlight;assembly=SilverlightViewMaker.Core""
    xmlns:i=""http://schemas.microsoft.com/expression/2010/interactivity""
    xmlns:it=""clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Input.Toolkit""
    xmlns:input=""clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Input""
    xmlns:toolkit=""clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Toolkit""
    IsTabStop=""False"" VerticalContentAlignment=""Stretch"" HorizontalContentAlignment=""Stretch""> 
    <ContentControl.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source=""/SilverlightViewMaker.Core;component/silverlight/slgenericresource.xaml""/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </ContentControl.Resources>  
</ContentControl>";

        }

        public string Generate(ViewLayoutItem rootItem)
        {
            if (rootItem == null) throw new ArgumentNullException("rootItem");
            var xaml = CreateTemplate(rootItem);
            var cont = rootItem.CreateXaml(xaml).LastOrDefault();
            if (cont != null) xaml.AppendChild(cont);
            return xaml.GetXamlCode();
        }

        private XamlNode CreateTemplate(ViewLayoutItem rootItem)
        {
            var xamlString = Template;
            if (rootItem.Element.WindowSettings != null && !string.IsNullOrWhiteSpace(rootItem.Element.WindowSettings.Template))
            {
                xamlString = rootItem.Element.WindowSettings.Template;
            }
            return XamlNode.LoadXaml(xamlString);
        }
    }
}
